const router = require('koa-router')()
const { pool } = require('../config/database')
const { authenticateToken, generateToken } = require('../middleware/auth')
const { hashPassword, comparePassword } = require('../utils/password')

router.prefix('/users')

// 用户注册
router.post('/register', async (ctx) => {
  try {
    const { username, password, email } = ctx.request.body
    
    if (!username || !password) {
      ctx.body = { success: false, error: '用户名和密码不能为空' }
      return
    }
    
    // 检查用户名是否已存在
    const [existingUsers] = await pool.execute(
      'SELECT id FROM users WHERE username = ?',
      [username]
    )
    
    if (existingUsers.length > 0) {
      ctx.body = { success: false, error: '用户名已存在' }
      return
    }
    
    // 加密密码
    const hashedPassword = await hashPassword(password)
    
    // 创建用户
    const [result] = await pool.execute(
      'INSERT INTO users (username, password, email) VALUES (?, ?, ?)',
      [username, hashedPassword, email]
    )
    
    ctx.body = { 
      success: true, 
      message: '注册成功',
      data: { userId: result.insertId }
    }
  } catch (error) {
    console.error('注册错误:', error)
    ctx.status = 500
    ctx.body = { success: false, error: '注册失败' }
  }
})

// 用户登录
router.post('/login', async (ctx) => {
  try {
    const { username, password } = ctx.request.body
    
    if (!username || !password) {
      ctx.body = { success: false, error: '用户名和密码不能为空' }
      return
    }
    
    // 查找用户
    const [users] = await pool.execute(
      'SELECT id, username, password, email, avatar FROM users WHERE username = ?',
      [username]
    )
    
    if (users.length === 0) {
      ctx.body = { success: false, error: '用户名或密码错误' }
      return
    }
    
    const user = users[0]
    
    // 验证密码
    const isValidPassword = await comparePassword(password, user.password)
    if (!isValidPassword) {
      ctx.body = { success: false, error: '用户名或密码错误' }
      return
    }
    
    // 生成JWT令牌
    const token = generateToken(user)
    
    ctx.body = {
      success: true,
      message: '登录成功',
      data: {
        token,
        userInfo: {
          id: user.id,
          username: user.username,
          email: user.email,
          avatar: user.avatar
        }
      }
    }
  } catch (error) {
    console.error('登录错误:', error)
    ctx.status = 500
    ctx.body = { success: false, error: '登录失败' }
  }
})

// 获取用户收藏列表
router.get('/favorites', authenticateToken, async (ctx) => {
  try {
    const [favorites] = await pool.execute(
      `SELECT f.id, f.song_id, f.song_title, f.artist, f.album, f.cover_url, f.add_time 
       FROM favorites f 
       WHERE f.user_id = ? 
       ORDER BY f.add_time DESC`,
      [ctx.user.id]
    )
    
    ctx.body = { 
      success: true, 
      data: favorites 
    }
  } catch (error) {
    console.error('获取收藏列表错误:', error)
    ctx.status = 500
    ctx.body = { success: false, error: '获取收藏列表失败' }
  }
})

// 添加收藏
router.post('/favorites', authenticateToken, async (ctx) => {
  try {
    const { songId, songTitle, artist, album, coverUrl } = ctx.request.body
    
    if (!songId || !songTitle) {
      ctx.body = { success: false, error: '歌曲信息不能为空' }
      return
    }
    
    // 检查是否已收藏
    const [existing] = await pool.execute(
      'SELECT id FROM favorites WHERE user_id = ? AND song_id = ?',
      [ctx.user.id, songId]
    )
    
    if (existing.length > 0) {
      ctx.body = { success: false, error: '歌曲已收藏' }
      return
    }
    
    // 添加收藏
    await pool.execute(
      'INSERT INTO favorites (user_id, song_id, song_title, artist, album, cover_url) VALUES (?, ?, ?, ?, ?, ?)',
      [ctx.user.id, songId, songTitle, artist, album, coverUrl]
    )
    
    ctx.body = { 
      success: true, 
      message: '添加收藏成功' 
    }
  } catch (error) {
    console.error('添加收藏错误:', error)
    ctx.status = 500
    ctx.body = { success: false, error: '添加收藏失败' }
  }
})

// 取消收藏
router.delete('/favorites', authenticateToken, async (ctx) => {
  try {
    const { songId } = ctx.request.body
    
    if (!songId) {
      ctx.body = { success: false, error: '歌曲ID不能为空' }
      return
    }
    
    const [result] = await pool.execute(
      'DELETE FROM favorites WHERE user_id = ? AND song_id = ?',
      [ctx.user.id, songId]
    )
    
    if (result.affectedRows === 0) {
      ctx.body = { success: false, error: '收藏记录不存在' }
      return
    }
    
    ctx.body = { 
      success: true, 
      message: '取消收藏成功' 
    }
  } catch (error) {
    console.error('取消收藏错误:', error)
    ctx.status = 500
    ctx.body = { success: false, error: '取消收藏失败' }
  }
})

// 检查歌曲是否已收藏
router.get('/favorites/check', authenticateToken, async (ctx) => {
  try {
    const { songId } = ctx.query
    
    if (!songId) {
      ctx.body = { success: false, error: '歌曲ID不能为空' }
      return
    }
    
    const [favorites] = await pool.execute(
      'SELECT id FROM favorites WHERE user_id = ? AND song_id = ?',
      [ctx.user.id, songId]
    )
    
    ctx.body = { 
      success: true, 
      data: { isFavorite: favorites.length > 0 } 
    }
  } catch (error) {
    console.error('检查收藏状态错误:', error)
    ctx.status = 500
    ctx.body = { success: false, error: '检查收藏状态失败' }
  }
})

router.get('/', function (ctx, next) {
  ctx.body = 'this is a users response!'
})

router.get('/bar', function (ctx, next) {
  ctx.body = 'this is a users/bar response'
})

module.exports = router
